<?php
namespace common\services;

use common\base\BaseActiveRecord;
use common\models\Ad;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;

class AdServices extends Ad
{

    /**
     * @param array $params
     * @return ActiveDataProvider
     */
    public function search($params = array()){
        $model = Ad::find(false);
        $model->orderBy('id desc');
        $dataProvider = new ActiveDataProvider([
            'query' => $model,
            'pagination' => [
                'pagesize' => $params['defaultPageSize'],
            ]
        ]);

        if (isset($params['position']) && $params['position'] != '') {
            $model->andFilterWhere(['=', 'position', $params['position']]);
        }
        if (isset($params['type']) && $params['type'] != '') {
            $model->andFilterWhere(['=', 'type', $params['type']]);
        }
        if (isset($params['status']) && $params['status'] != '') {
            $model->andFilterWhere(['=', 'status', $params['status']]);
        }

        if (!empty($params['keywords'])){
            $model->andFilterWhere(['like', 'title', $params['keywords']]);
        }


        return $dataProvider;
    }

    /**
     * @param $position
     * @param bool $withCache
     * @return mixed|null|static
     */
    public function getAdByPosition($position, $withCache = true){
        $cacheKey = 'ad_position_'.$position;
        $result = $withCache ? \Yii::$app->cache->get($cacheKey) : false;
        if ($result === false) {
            $result = Ad::findAll(['position' => $position, 'status' => self::STATUS_FLAG_NORMAL]);
            if (!empty($result) && $withCache){
                \Yii::$app->cache->set($cacheKey, $result);
            }
        }
        return $result;
    }

}
